// initialize 
THUMB_WIDTH = 50;
THUMB_HEIGHT = 50;
THUMB_MARGIN_X = 10;
THUMB_MARGIN_Y = 10;
NAME_HEIGHT = 15;
NAME_MARGIN_TOP=5;
MEMBER_COUNT=60;
QIN_TREE_WIDTH = 760;
QIN_TREE_HEIGHT = QIN_TREE_WIDTH;
RELATIVE_LINE_HEIGHT = 50;
MORE_BUTTON_WIDTH = 50;
MORE_BUTTON_HEIGHT = 20;
MEMBER_BLOCK_HEIGHT = THUMB_HEIGHT + NAME_HEIGHT + THUMB_MARGIN_X + NAME_MARGIN_TOP;
FONT = "15px 宋体";
BASE_LINE = "top";
COLUMN = 9;
prev_x = 0;
prev_y = 0;

members = [];
family = new Array();
canvas_margin_left = 0;
canvas_margin_top = 0;

var canvas = document.getElementById("canvas");
var cxt = canvas.getContext("2d");
var canvas_top = document.getElementById("canvas_top");
var cxt_top = canvas_top.getContext("2d");

function log(str)
{
    $("#msg1").html($("#msg1").html()+ str+"<br/>");
}
function pageX(elem) {//获取元素相对于整个文档的X位置的函数；
    var p = 0;
    while ( elem.offsetParent ) {
        p += elem.offsetLeft;
        elem = elem.offsetParent;
    }
    return p;
}
function pageY(elem){ //获取元素相对于整个文档的Y位置的函数；
    var p = 0;
    while ( elem.offsetParent ) {
        p += elem.offsetTop;
        elem = elem.offsetParent;
    }
    return p;
}
function getMember(e)
{
    var mouse_x = e.pageX - canvas_margin_left;
    var mouse_y = e.pageY - canvas_margin_top;
    // search which member is hovered
    for(var i=0; i<members.length; i++)
    {
	if (mouse_x >= members[i].x1 && mouse_x <= members[i].x2 &&
	    mouse_y >= members[i].y1 && mouse_y <= members[i].y2)
	{
	    break;
	}
    }
    var a= members[i];
    return a;
}
function selectMember(e, color)
{
    log(" page x: "+e.pageX+"; page y: "+e.pageY);
    var member = getMember(e);

    var x = member.x1;
    var y = member.y1;
    // log("x1: "+x+"; y1: "+y+"; x2: "+members[i].x2+"; y2: "+members[i].y2);
    // var x = Math.floor((e.pageX-$("#canvas").offset().left) / (THUMB_WIDTH+THUMB_MARGIN_X)) * (THUMB_WIDTH+THUMB_MARGIN_X);
    // var y = Math.floor((e.pageY-$("#canvas").offset().top) / (MEMBER_BLOCK_HEIGHT + RELATIVE_LINE_HEIGHT)) * (MEMBER_BLOCK_HEIGHT + RELATIVE_LINE_HEIGHT);

    // in the same block, do nothing
    if (prev_x == x && prev_y == y)
	return;

    // move to another block, update the new block position
    prev_x = x;
    prev_y = y;

    // clear the mast layer and stroke the new border
    // var canvas_top = $("#canvas_top")[0];
    // canvas_top.width = canvas_top.width;
    // canvas_top.height = canvas_top.height;
    // var cxt = canvas_top.getContext("2d");
    // cxt1.clearRect(0,0,QIN_TREE_WIDTH,QIN_TREE_HEIGHT);
    // log("cxt1.width = "+canvas_top.width);
    // log("cxt1.height = "+canvas_top.height);
    // cxt1.moveTo(x, y);
    // cxt1.lineTo(x+THUMB_WIDTH, y+THUMB_HEIGHT);
    clearCanvas("canvas_top");
    cxt_top.strokeStyle = color;
    cxt_top.strokeRect(x, y, THUMB_WIDTH, THUMB_HEIGHT + NAME_HEIGHT + NAME_MARGIN_TOP);
    cxt_top.stroke();
}

function clearCanvas(id)
{
    var canvas = document.getElementById(id);
    canvas.width = canvas.width;
    canvas.height = canvas.height;
}
$(document).ready(function(){
    // $("#canvas").mousemove(function(e){
    // 	log(" x: "+e.pageX+"; y: "+e.pageY);
    // });
    $("#canvas").hover(function(e){
	return false;
    });
    $("#canvas_top").click(function(e){
	//$("#msg").html($("#msg").html() + "click me <br/>");
	log("click  x: "+e.pageX+"; y: "+e.pageY);
	selectMember(e, "blue");
    });
    $("#canvas_top").dblclick(function(e){
	//$("#msg").html($("#msg").html() + "click me <br/>");
	log("dbclick  x: "+e.pageX+"; y: "+e.pageY);
	selectMember(e, "red");
	var member = getMember(e);
	$.getJSON("get-relatives.php?id="+member.id,
		  function(tree){
		      // clear canvas
		      clearCanvas("canvas");
		      clearCanvas("canvas_top");
		      // var canvas = document.getElementById("canvas");
		      // canvas.width = canvas.width;
		      // canvas.height = canvas.height;
		      // log("canvas.width = "+canvas.width);
		      // log("canvas.height = "+canvas.height);
		      // var cxt = canvas.getContext("2d");
		      // cxt.clearRect(0,0,QIN_TREE_WIDTH,QIN_TREE_HEIGHT);

		      // clear top canvas
		      // var canvas = document.getElementById("canvas");
		      // canvas.width = canvas.width;
		      // canvas.height = canvas.height;
		      

		      drawMemberTree(cxt, 0, 0, QIN_TREE_WIDTH, tree);
		  });
    });
    var canvas = $("#canvas_top")[0];	
    // canvas.addEventListener('mousemove', onMouseMove, false); 
    // canvas.addEventListener('mousedbclick', onMouseMove, false); 

    canvas_margin_left = pageX(canvas);//.offsetLeft;// + canvas.clientLeft;
    canvas_margin_top = pageY(canvas);//.offsetTop;// + canvas.clientTop;
    // log("canvas.clientTop: "+canvas.clientTop);
    log("canvas_margin_left: "+canvas_margin_left);
    log("canvas_margin_top: "+canvas_margin_top);
});
function onMouseMove(e){
    log("on move ");
    selectMember(e, "blue");
}

// draw a member on a canvas
function drawMember(context, url, name, x, y)
{
    var img = new Image();
    img.onload = function(){context.drawImage(img, x, y, THUMB_WIDTH, THUMB_HEIGHT);};
    log("name: "+name+"; x: "+x+"; y: "+ y+"; width: "+ THUMB_WIDTH+"; height: " +THUMB_HEIGHT);
    img.src = url;
    context.font = FONT; 
    context.textBaseline = BASE_LINE;
    context.fillText(name, x,y+THUMB_HEIGHT+NAME_MARGIN_TOP);
}

// 
function drawMemberTree(cxt, x1, y, x2, tree)
{
    // log("-------------------------------");
    // log(tree.name);

    // if mate exists
    if (tree.mate)
    {
	var xm = x1 + (x2- x1- THUMB_WIDTH*2 - THUMB_MARGIN_X)/2;
	drawMember(cxt, tree.avatar, tree.name, xm, y);
	// var o = ;
	members.push({id:tree.id, name:tree.name, x1: xm, y1: y, x2: xm+THUMB_WIDTH, y2:y+THUMB_HEIGHT});
	drawMember(cxt, tree.mate.avatar, tree.mate.name, (xm + THUMB_WIDTH + THUMB_MARGIN_X), y);
	members.push({id:tree.mate.id, name:tree.mate.name, 
		      x1: (xm + THUMB_WIDTH + THUMB_MARGIN_X), y1: y, 
		      x2: (xm + THUMB_WIDTH + THUMB_MARGIN_X)+THUMB_WIDTH, y2:y+THUMB_HEIGHT});
	var root_x = xm + THUMB_WIDTH + THUMB_MARGIN_X / 2;
    }
    else
    {
	var xm = x1 + (x2 - x1 - THUMB_WIDTH) / 2;
	drawMember(cxt, tree.avatar, tree.name, xm, y);
	var root_x = xm + THUMB_WIDTH / 2;
	members.push({id:tree.id, name:tree.name, 
		      x1: xm, y1: y, 
		      x2: xm+THUMB_WIDTH, y2:y+THUMB_HEIGHT});
    }
    var root_y = y + MEMBER_BLOCK_HEIGHT;

    // draw the children
    if (tree.children && tree.children.length>0)
    {
	var len = tree.children.length;
	var more_btn = false;
	$.each(tree.children, function(i, subtree){
	    if (more_btn)
		return;

	    var child_width = ((x2-x1) / len) > (THUMB_WIDTH+THUMB_MARGIN_X) ? ((x2-x1) / len) : (THUMB_WIDTH+THUMB_MARGIN_X);
	    var child_x1 = x1 + i * child_width;
	    var child_x2 = x1 + (i+1) * child_width;
	    var head_x = (child_x1 + child_x2) / 2;
	    var head_y = y + MEMBER_BLOCK_HEIGHT + RELATIVE_LINE_HEIGHT;

	    // draw a line from root to this child
	    cxt.moveTo(root_x, root_y);
	    cxt.lineWidth = 1;
	    cxt.lineTo(head_x, head_y);
	    cxt.stroke();

	    // 还有1一个以上成员，且画面不足以放下当前成员和一个more按钮时，不再描画本成员，描画按钮，并退出。
	    if (!more_btn && (i+2) < len && (child_x2 + MORE_BUTTON_WIDTH) > x2)
	    {
	    	cxt.strokeRect(child_x1, head_y, MORE_BUTTON_WIDTH, MORE_BUTTON_HEIGHT);
	    	more_btn = true;
	    	return;
	    }

	    // draw the subtree of this child
	    drawMemberTree(cxt, child_x1, head_y, child_x2, subtree);
	});
    }
}

$.getJSON("get-relatives.php",
	  function(tree){
	      //alert("xxx");
	      drawMemberTree(cxt, 0, 0, QIN_TREE_WIDTH, tree);
	  });

// alert(members.length);
